#!/usr/bin/env python3
"""
验证过滤器是否真正工作的测试脚本
"""

import requests
import json
import sqlite3

def analyze_database():
    """分析数据库中的实际数据"""
    print("=== 分析数据库数据 ===")
    
    try:
        conn = sqlite3.connect('db/trades.db')
        cursor = conn.cursor()
        
        # 总记录数
        cursor.execute('SELECT COUNT(*) FROM trades')
        total_count = cursor.fetchone()[0]
        print(f"总记录数: {total_count}")
        
        # 品种统计
        cursor.execute('SELECT symbol, COUNT(*) FROM trades GROUP BY symbol ORDER BY COUNT(*) DESC LIMIT 10')
        symbols = cursor.fetchall()
        print(f"品种统计: {symbols}")
        
        # 方向统计
        cursor.execute('SELECT direction, COUNT(*) FROM trades GROUP BY direction')
        directions = cursor.fetchall()
        print(f"方向统计: {directions}")
        
        # 净利润范围
        cursor.execute('SELECT MIN(net_profit), MAX(net_profit), AVG(net_profit) FROM trades WHERE net_profit IS NOT NULL')
        profit_stats = cursor.fetchone()
        print(f"净利润范围: 最小={profit_stats[0]}, 最大={profit_stats[1]}, 平均={profit_stats[2]:.2f}")
        
        # 检查是否有AAPL和TSLA数据
        cursor.execute('SELECT COUNT(*) FROM trades WHERE symbol = "AAPL"')
        aapl_count = cursor.fetchone()[0]
        print(f"AAPL记录数: {aapl_count}")
        
        cursor.execute('SELECT COUNT(*) FROM trades WHERE symbol = "TSLA"')  
        tsla_count = cursor.fetchone()[0]
        print(f"TSLA记录数: {tsla_count}")
        
        # 检查测试数据
        cursor.execute('SELECT COUNT(*) FROM trades WHERE trade_id LIKE "T%"')
        test_count = cursor.fetchone()[0]
        print(f"测试数据记录数: {test_count}")
        
        conn.close()
        return {
            'total': total_count,
            'symbols': symbols,
            'directions': directions,
            'aapl_count': aapl_count,
            'tsla_count': tsla_count,
            'test_count': test_count
        }
        
    except Exception as e:
        print(f"数据库分析错误: {e}")
        return None

def test_no_filter():
    """测试无过滤器的情况"""
    print("\n=== 测试无过滤器 ===")
    
    try:
        response = requests.get('http://localhost:5000/statistics/chart_data', timeout=10)
        
        if response.status_code == 200:
            data = response.json()
            if isinstance(data, dict) and 'trades' in data:
                trades = data['trades']
                total = data.get('total', len(trades))
                print(f"无过滤器返回: {len(trades)} 条记录 (总计: {total})")
                
                # 显示前5条记录
                for i, record in enumerate(trades[:5]):
                    symbol = record.get('symbol', 'N/A')
                    direction = record.get('direction', 'N/A')
                    net_profit = record.get('net_profit', 'N/A')
                    print(f"  记录 {i+1}: {symbol} - {direction} - {net_profit}")
                
                return len(trades)
            else:
                print(f"响应格式异常: {data}")
                return 0
        else:
            print(f"HTTP错误: {response.status_code}")
            return 0
            
    except Exception as e:
        print(f"请求异常: {e}")
        return 0

def test_specific_filters(db_stats):
    """测试特定的过滤器"""
    print("\n=== 测试特定过滤器 ===")
    
    # 根据数据库实际数据创建测试用例
    test_cases = []
    
    # 如果有符合条件的数据，创建对应的测试用例
    if db_stats and db_stats['symbols']:
        # 使用实际存在的品种
        actual_symbol = db_stats['symbols'][0][0]  # 第一个品种
        test_cases.append({
            'name': f'品种过滤测试 - {actual_symbol}',
            'filters': [{'field': 'symbol', 'operator': 'equals', 'value': actual_symbol}],
            'expected_count': db_stats['symbols'][0][1]
        })
    
    # 方向过滤
    if db_stats and db_stats['directions']:
        actual_direction = db_stats['directions'][0][0]  # 第一个方向
        test_cases.append({
            'name': f'方向过滤测试 - {actual_direction}',
            'filters': [{'field': 'direction', 'operator': 'equals', 'value': actual_direction}],
            'expected_count': db_stats['directions'][0][1]
        })
    
    # 数值过滤 - 净利润大于0
    test_cases.append({
        'name': '净利润大于0',
        'filters': [{'field': 'net_profit', 'operator': 'greater_than', 'value': '0'}],
        'expected_count': None  # 不知道确切数量
    })
    
    # 数值过滤 - 净利润小于0
    test_cases.append({
        'name': '净利润小于0',
        'filters': [{'field': 'net_profit', 'operator': 'less_than', 'value': '0'}],
        'expected_count': None
    })
    
    success_count = 0
    
    for test_case in test_cases:
        print(f"\n{test_case['name']}:")
        print(f"  过滤器: {test_case['filters']}")
        
        try:
            request_data = {'filters': test_case['filters']}
            response = requests.get(
                'http://localhost:5000/statistics/chart_data',
                params={'config': json.dumps(request_data)},
                timeout=10
            )
            
            if response.status_code == 200:
                data = response.json()
                if isinstance(data, dict) and 'trades' in data:
                    trades = data['trades']
                    total = data.get('total', len(trades))
                    print(f"  ✓ 返回 {len(trades)} 条记录 (总计: {total})")
                    
                    # 验证结果
                    if test_case['expected_count'] is not None:
                        if len(trades) == test_case['expected_count']:
                            print(f"  ✓ 记录数匹配预期")
                            success_count += 1
                        else:
                            print(f"  ⚠ 记录数不匹配，预期 {test_case['expected_count']}")
                    else:
                        success_count += 1
                    
                    # 显示前3条记录
                    for i, record in enumerate(trades[:3]):
                        symbol = record.get('symbol', 'N/A')
                        direction = record.get('direction', 'N/A')
                        net_profit = record.get('net_profit', 'N/A')
                        print(f"    记录 {i+1}: {symbol} - {direction} - {net_profit}")
                        
                else:
                    print(f"  ✗ 响应格式异常")
            else:
                print(f"  ✗ HTTP错误: {response.status_code}")
                
        except Exception as e:
            print(f"  ✗ 请求异常: {e}")
    
    print(f"\n过滤器测试结果: {success_count}/{len(test_cases)} 成功")
    return success_count == len(test_cases)

def main():
    """主函数"""
    print("验证过滤器是否真正工作")
    print("=" * 40)
    
    # 分析数据库
    db_stats = analyze_database()
    
    # 测试无过滤器
    no_filter_count = test_no_filter()
    
    # 测试特定过滤器
    filter_success = test_specific_filters(db_stats)
    
    print(f"\n=== 总结 ===")
    if db_stats:
        print(f"数据库总记录数: {db_stats['total']}")
        print(f"无过滤器API返回: {no_filter_count} 条记录")
        
        if no_filter_count == db_stats['total']:
            print("✓ 无过滤器测试通过")
        else:
            print("⚠ 无过滤器测试记录数不匹配")
    
    if filter_success:
        print("✓ 过滤器功能正常工作")
    else:
        print("⚠ 过滤器功能可能存在问题")
    
    print("\n建议:")
    print("1. 如果所有过滤器都返回相同的记录数，说明过滤器可能没有正确应用")
    print("2. 检查前端页面的过滤器UI是否正确发送过滤条件")
    print("3. 检查后端API是否正确处理过滤条件")

if __name__ == '__main__':
    main() 